﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Drawing.Printing;


namespace WindowsFormsAppOpenFile
{
    class AutoPrinter
    {
        public void PrintText(string textToPrint, string printerName = null)
    {
        PrintDocument pd = new PrintDocument();
        
        if (!string.IsNullOrEmpty(printerName))
        {
            pd.PrinterSettings.PrinterName = printerName;
        }

        pd.PrintPage += (sender, args) =>
        {
            Font printFont = new Font("Arial", 10);
            args.Graphics.DrawString(textToPrint, printFont, Brushes.Black, 
                new RectangleF(0, 0, pd.DefaultPageSettings.PrintableArea.Width, 
                              pd.DefaultPageSettings.PrintableArea.Height));
        };

        try
        {
            pd.Print();
        }
        catch (Exception ex)
        {
            Console.WriteLine("打印错误: " + ex.Message);
        }
    }
    }
}
